/*
 * MemMonitor_F.cpp
 *
 *  Created on: Aug 30, 2012
 *      Author: lucid
 */
#include "comm_lib_f.h"
#include <unistd.h>
#include <string.h>
#include <string>
using std::string;
#include <vector>
using std::vector;


#include "mem_monitor_f.h"
#include "file_f.h"


mem_monf_t::mem_monf_t()
{
	m_pFileReport = 0;
	m_dwUSecond = 0;
	m_iPID = 0;
	m_bMonitorLoop = 0;
	_snapshot_info.resize(512);
}

mem_monf_t::~mem_monf_t()
{

}

int mem_monf_t::init(FILE* pFile,__useconds_t uSecond,int iPID)
{
	return set_recordfile(pFile)
			&& set_record_intv(uSecond)
			&& set_record_pid(iPID);
}

int mem_monf_t::set_recordfile(FILE* pFile)
{
	if(0 == pFile)
		return RETURN_ERROR_F;
	m_pFileReport = pFile;
	return RETURN_SUCCESS_F;
}

int mem_monf_t::set_record_intv(__useconds_t uSecond)
{
	m_dwUSecond = uSecond;
	return RETURN_SUCCESS_F;
}

int mem_monf_t::set_record_pid(__pid_t iPID)
{
	if(-1 == iPID)
		m_iPID = getpid();
	else
		m_iPID = iPID;
	return RETURN_SUCCESS_F;
}

int mem_monf_t::start()
{
	return m_ThMonitor.create(MonitorThread,this);
}

int mem_monf_t::pause()
{
	return m_ThMonitor.SuspendThread();
}

int mem_monf_t::resume()
{
	return m_ThMonitor.ResumeThread();
}

int mem_monf_t::stop()
{
	if (0 == m_bMonitorLoop)
		return RETURN_ERROR_F;
	m_bMonitorLoop = 0;
	return RETURN_SUCCESS_F;
}

//static
void* mem_monf_t::MonitorThread(void* pData)
{
	mem_monf_t* pThis = (mem_monf_t*)pData;
	return pThis->MonitorImpl();
}

void* mem_monf_t::MonitorImpl()
{
	m_bMonitorLoop = 1;
	while(m_bMonitorLoop)
	{
		if (m_pFileReport) {
			fprintf(m_pFileReport,dump_snapshot());
		}
		usleep(m_dwUSecond);
	}
	return 0;
}

const char* mem_monf_t::dump_snapshot()
{
	if (0 ==  m_pFileReport)
		return NULL;

	char ch[512];
	const string chTempFile = clib_get_proc_path() + "TempInfo";
	sprintf(ch,"cat /proc/%d/status > %s",int(m_iPID),chTempFile.c_str());
	system(ch);

	filef_t file;
	file.open_exist(chTempFile.c_str(),filef_t::FILE_ACCESS_FLAG_RDWR);

	vector<char> chFile(file.get_len());
	file.read(0,&chFile[0],file.get_len());

	string str(&chFile[0]);
	string::size_type iPosSta,iPosEnd;
	iPosSta = str.find("VmRSS:") + strlen("VmRSS:");
	iPosSta = str.find_first_not_of(" \t",iPosSta);
	iPosEnd = str.find_first_of(' ',iPosSta);

	int iLen = iPosEnd-iPosSta;

	vector<char> vChVmRSS(iLen+1,0);
	memcpy(&vChVmRSS[0],&str[iPosSta],iLen);

	time_t tNow;
	tNow = time(&tNow);
	struct tm* tmNow = localtime(&tNow);

	sprintf(&_snapshot_info[0],"%04d_%02d_%02d,%02d:%02d:%02d Memory = %s k\n",
			tmNow->tm_year+1900,tmNow->tm_mon,tmNow->tm_mday,
			tmNow->tm_hour,tmNow->tm_min,tmNow->tm_sec,
			&vChVmRSS[0]);

	return _snapshot_info.c_str();
}


















